<?php

namespace App\Admin\Controllers;

use App\Lib\Uploads\UploadHandler;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\WxShopClassify;
use App\Models\WxShopGoods;
use App\Models\WxShopGoodsProduct;
use App\Models\WxShopService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;


class WxShopGoodsController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WxShopGoods(), function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->column('id')->sortable();
            $grid->column('name')->limit(20);
//            $grid->column('pic');
//            $grid->column('tag');
//            $grid->column('intro');
            $grid->column('vip_price');
            $grid->column('price');
//            $grid->column('content');
            $grid->column('views');
            $grid->column('buys');
//            $grid->column('sku');
//            $grid->column('classify_id');
//            $grid->column('service_id');
            $grid->column('sort')->editable();
            $grid->column('is_inspiration','灵感')->switch();
            $grid->column('state')->switch();
            $grid->column('created_at');
//            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxShopGoods(), function (Show $show) {
            $show->field('id');
            $show->field('name');
//            $show->field('pic');
//            $show->field('tag');
            $show->field('intro');
            $show->field('vip_price');
            $show->field('price');
            $show->field('content');
            $show->field('views');
            $show->field('buys');
            $show->field('sort');
            $show->field('sku');
//            $show->field('classify_id');
//            $show->field('service_id');
            $show->field('state');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WxShopGoods(), function (Form $form) {
            $form->display('id');
            $form->text('name','商品名称');
            $form->text('vip_price','商品VIP价格');
            $form->text('price','商品价格');
            $form->textarea('intro','商品介绍');

            $options = WxShopClassify::pluck('name','id')->toArray();
            $form->select('classify_id','商品分类')->options($options);

            $form->tags('tag','标签')
                ->options(['上新'])
                ->help('使用，隔开 建议添加1～3个标签');

            $form->multipleSelect('service_id','服务')
                ->options(WxShopService::pluck('name','id'));

            $form->multipleImage('pic', '图片')->uniqueName()->url('files/uploads')
                ->autoUpload()->sortable();

            $sku_params = [];
            $form->sku('sku', json_encode($sku_params))->display(true)->customFormat(function ($value) use ($form){
                if($value){
                    // 这里是给sku喂数据， 数据格式为
                    $data = (new WxShopGoods())->where('id',$form->getKey())->value('sku');

                    return $data;
                }
                return null;
            });

            $form->editor('content','详情');
            $form->text('views','点击数')->default(0);
            $form->text('buys','购买数')->default(0);
            $form->number('sort','排序');
            $form->switch('is_inspiration','灵感');
            $form->switch('state','状态');

            $form->display('created_at');
            $form->display('updated_at');

            if ($form->isEditing()) {
                $id = $form->getKey();
                $form->action('shop/save_goods/'.$id);
            }else{
                $form->action('shop/add_goods');
            }
        });
    }


    public function add(Request $request){

        $input = $request->all();
        $tag = $input['tag'];
        unset($tag[count($tag)-1]);
        $service = $input['service_id'];
        unset($service[count($service)-1]);

        // 保存商品
        $GoodsModel = new WxShopGoods();
        $GoodsModel->name = $input['name'];
        $GoodsModel->pic = $input['pic'];
        $GoodsModel->vip_price = $input['vip_price'];
        $GoodsModel->price = $input['price'];
        $GoodsModel->classify_id = $input['classify_id'];
        $GoodsModel->content = $input['content'];
        $GoodsModel->views = $input['views'];
        $GoodsModel->buys = $input['buys'] ? $input['buys']:0;
        $GoodsModel->state = $input['state'];
        $GoodsModel->sku = $input['sku'];
        $GoodsModel->intro = $input['intro'];
        $GoodsModel->service_id = json_encode($service);
        $GoodsModel->tag = json_encode($tag);
        $GoodsModel->save();

        $goods_id = $GoodsModel->id;

        // 保存产品

        $params = json_decode($input['sku'],true);

        $sku = $params['sku'];
        $attrs = $params['attrs'];
        $attrsArr = array_values($attrs);
        $attrsArr = $this->brush([],$attrsArr);

        $productData = [];
        foreach ($attrsArr as $k=>$v){
            $productData[] = [
                'goods_id' => $goods_id,
                'vip_price'=>$sku[$k]['vip_price'],
                'price'=>$sku[$k]['price'],
                'stock'=>$sku[$k]['stock'],
                'pic'=>$sku[$k]['pic'],
                'param_value'=>$v,
                'created_at'=>date('Y-m-d H:i:s')
            ];
        }
        (new WxShopGoodsProduct())->batchAdd($productData);

        return JsonResponse::make()->success('成功！')->redirect('shop/goods');
    }


    public function save(Request $request,$goods_id){

        $input = $request->all();

        if($request['_method']){
            $tag = $input['tag'];
            unset($tag[count($tag)-1]);
            // 删除原有产品
            (new WxShopGoodsProduct())->where('goods_id',$goods_id)->delete();
            // 更新商品
            (new WxShopGoods())->where('id',$goods_id)
                ->update([
                    'name'=>$input['name'],
                    'pic'=>$input['pic'],
                    'vip_price'=>$input['vip_price'],
                    'price'=>$input['price'],
                    'intro'=>$input['intro'],
                    'content'=>$input['content'],
                    'views'=>$input['views'],
                    'buys'=>$input['buys'],
                    'state'=>$input['state'],
                    'sku'=>$input['sku'],
                    'tag'=> json_encode($tag),
                    'classify_id'=>$input['classify_id'],
                    'service_id'=>$input['service_id']
                ]);

            $params = json_decode($input['sku'],true);

            $sku = $params['sku'];
            $attrs = $params['attrs'];

            $attrsArr = array_values($attrs);

            $attrsArr = $this->brush([],$attrsArr);

            $productData = [];
            foreach ($attrsArr as $k=>$v){
                $productData[] = [
                    'goods_id' => $goods_id,
                    'vip_price'=>$sku[$k]['vip_price'],
                    'price'=>$sku[$k]['price'],
                    'stock'=>$sku[$k]['stock'],
                    'pic'=>$sku[$k]['pic'],
                    'param_value'=>$v,
                    'created_at'=>date('Y-m-d H:i:s')
                ];
            }
            (new WxShopGoodsProduct())->batchAdd($productData);

            return JsonResponse::make()->success('成功！')->redirect('shop/goods');
        }


    }



    public function brush($res = [], $arr = [])
    {
        if (empty($res)) $res = (array)array_shift($arr);
        if (empty($arr)) return $res;
        $current = array_shift($arr); # 接下来要参与计算的一组属性
        $last = [];
        foreach ($res as $row => $row_val) { # 循环上一次已经算出的集合
            foreach ($current as $col => $col_val) {
                $last[] = $row_val . '_' . $col_val;
            }
        }
        return $this->brush($last,$arr); # 递归处理, 直到$arr滚到最后一组属性
    }


    /**
     * 上传商品规格图片
     *
     * @param Request $request
     *
     * @return string[]
     */
    public function skuImage(Request $request)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');

            $path = UploadHandler::handle($file);

            return ['url' => $path['url']];

//            // 返回格式
//            $disk = Storage::disk('cosv5');
//            $url = 'sku';
//            $res = $disk->put($url, $file);
//            return ['url' => config('filesystems.disks.cosv5.cdn') .'/'. $res];
        }
        return [];
    }
}
